using UnityEngine;
using RPG.Infrastructure.Events;
using RPG.Infrastructure.Persistence;
using RPG.Application.Services.Character;
using RPG.Application.EventHandlers.Character;
using RPG.Domain.Character;

namespace RPG.Presentation.Core
{
    public class GameManager : MonoBehaviour
    {
        private static GameManager _instance;
        public static GameManager Instance => _instance;

        private IEventBus _eventBus;
        private ICharacterService _characterService;
        private IRepository<Character, CharacterId> _characterRepository;

        private void Awake()
        {
            if (_instance != null && _instance != this)
            {
                Destroy(gameObject);
                return;
            }
            _instance = this;
            DontDestroyOnLoad(gameObject);

            InitializeGame();
        }

        private void InitializeGame()
        {
            // 初始化事件总线
            _eventBus = new UnityEventBus();

            // 初始化仓储
            _characterRepository = new UnityRepository<Character, CharacterId>("Character");

            // 初始化服务
            _characterService = new CharacterService(_characterRepository, _eventBus);

            // 注册事件处理器
            RegisterEventHandlers();
        }

        private void RegisterEventHandlers()
        {
            _eventBus.Subscribe(new CharacterCreatedEventHandler());
            _eventBus.Subscribe(new CharacterLevelUpEventHandler());
            _eventBus.Subscribe(new ItemEquippedEventHandler());
        }

        // 提供访问服务的方法
        public ICharacterService GetCharacterService() => _characterService;
        public IEventBus GetEventBus() => _eventBus;
    }
}
